package com.hoodbrains.insideloc.guidedshopping;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.hoodbrains.insideloc.R;
import com.hoodbrains.insideloc.maps.Magasin;
import com.hoodbrains.insideloc.shopping.ShoppingItem;
import com.hoodbrains.insideloc.shopping.ShoppingList;
import com.hoodbrains.insideloc.utils.Catalog;
import com.hoodbrains.insideloc.utils.ItemHolder;

public class ProductListAdapter extends BaseAdapter {
	
	private LayoutInflater inflater;
	private OnClickListener listener;
	
	private ShoppingList model;
	private List<ShoppingItem> items;
	
	public ProductListAdapter(Context ctx, OnClickListener listener, ShoppingList model) {
		this.listener = listener;
		this.model = model;
		inflater = LayoutInflater.from(ctx);
		model.registerAdapter(this);
		this.items = model.getItemList();
	}

	
	@Override
	public boolean hasStableIds() {
		return true;
	}

	/**
	 * Refresh the source elements list before repaint.
	 */
	@Override
	public void notifyDataSetChanged() {
		items = model.getItemList();
		
		super.notifyDataSetChanged();
	}


	public View getView(int position, View convertView, ViewGroup parent) {
		
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.shop_list_item, parent, false);
		}
		
		TextView name = (TextView) convertView.findViewById(R.id.produit_sli);
		CheckBox cbx = (CheckBox)convertView.findViewById(R.id.checkbox_sli);
		
		ShoppingItem item = getItem(position);
		name.setText(item.getName());
		String color = Catalog.getInstance().getColor(item.getRayon());

		name.setTextColor(Color.parseColor(color));
		
		ItemHolder<ShoppingItem> iH = new ItemHolder<ShoppingItem>(item, position, -1);

		cbx.setChecked(item.isGrabbed());
		cbx.setEnabled(!item.isGrabbed());
		cbx.setTag(iH);
		cbx.setOnClickListener(listener);
		
		return convertView;
		
	}



	public int getCount() {
		return items.size();
	}



	public ShoppingItem getItem(int position) {
		return items.get(position);
	}


	public long getItemId(int position) {
		return -1;
	}
}
